package com.ghh.init;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ghh.constant.RedisConstant;
import com.ghh.service.SetmealService;
import com.ghh.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;

import java.util.Set;

@Component
public class InitJob {

    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;

    //初始化容器时 执行该方法 即每隔一分钟 清理一下远程的服务器
    // @Scheduled(cron = "0/30 * * * * ?")
    public void cleanImg() {
        System.out.println("定时任务开始了");
        //从七牛云获取所有文件的名字,并存入Redis中
        Set<String> setQiNiu = QiniuUtils.getAllFileName();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,setQiNiu.toArray(new String[setQiNiu.size()]));

        //从数据库获取所有文件的名字，并存入Redis中
        Set<String> setDB = setmealService.findAllFileName();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,setDB.toArray(new String[setDB.size()]));

        //比较两个集合的缓存 得到无效的图片
        Set<String> imgSet = jedisPool.getResource().sdiff(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);

        if (imgSet != null) {
            for (String img : imgSet) {
                //删除云端的图片
                QiniuUtils.deleteFileFromQiniu(img);
                //删除缓存的图片
                jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES,img);
            }
            System.out.println("删除了无效的图片");
        }
    }
}
